class Game {
    constructor() {
        // 获取DOM元素
        this.canvas = document.getElementById('gameCanvas');
        this.overlay = document.getElementById('gameOverlay');
        this.overlayText = document.getElementById('overlayText');
        this.scoreElement = document.getElementById('score');
        this.levelElement = document.getElementById('level');

        // 初始化游戏组件
        this.gameBoard = new GameBoard(14, 10); // 调整行数以适应新的屏幕大小
        this.renderer = new Renderer(this.canvas);
        this.currentBlock = null;
        this.nextBlock = null;

        // 游戏状态
        this.score = 0;
        this.level = 1;
        this.gameOver = false;
        this.isPaused = false;

        // 游戏速度（下落间隔，毫秒）
        this.dropInterval = 1000;
        this.dropCounter = 0;
        this.lastTime = 0;

        // 初始化游戏
        this.init();
    }

    init() {
        // 创建初始方块
        this.currentBlock = new Block();
        this.nextBlock = new Block();

        // 设置按钮事件监听
        this.setupControls();

        // 开始游戏循环
        requestAnimationFrame(this.gameLoop.bind(this));
    }

    setupControls() {
        // 方向键控制
        document.getElementById('btnLeft').addEventListener('click', () => this.moveBlock(-1, 0));
        document.getElementById('btnRight').addEventListener('click', () => this.moveBlock(1, 0));
        document.getElementById('btnDown').addEventListener('click', () => this.moveBlock(0, 1));
        document.getElementById('btnUp').addEventListener('click', () => this.rotateBlock());

        // 按钮控制
        document.getElementById('btnA').addEventListener('click', () => this.rotateBlock());
        document.getElementById('btnB').addEventListener('click', () => this.hardDrop());
        document.getElementById('btnStart').addEventListener('click', () => this.togglePause());
        document.getElementById('btnSelect').addEventListener('click', () => this.resetGame());

        // 键盘控制
        document.addEventListener('keydown', (e) => {
            if (this.gameOver) return;

            switch (e.key) {
                case 'ArrowLeft':
                    this.moveBlock(-1, 0);
                    break;
                case 'ArrowRight':
                    this.moveBlock(1, 0);
                    break;
                case 'ArrowDown':
                    this.moveBlock(0, 1);
                    break;
                case 'ArrowUp':
                    this.rotateBlock();
                    break;
                case 'z':
                case 'Z':
                    this.rotateBlock();
                    break;
                case 'x':
                case 'X':
                    this.hardDrop();
                    break;
                case 'p':
                case 'P':
                    this.togglePause();
                    break;
                case 'r':
                case 'R':
                    this.resetGame();
                    break;
            }
        });
    }

    gameLoop(time) {
        const deltaTime = time - this.lastTime;
        this.lastTime = time;

        if (!this.isPaused && !this.gameOver) {
            this.dropCounter += deltaTime;

            if (this.dropCounter > this.dropInterval) {
                this.moveBlock(0, 1);
                this.dropCounter = 0;
            }
        }

        this.draw();
        requestAnimationFrame(this.gameLoop.bind(this));
    }

    draw() {
        this.renderer.clear();
        this.renderer.drawBoard(this.gameBoard);

        if (this.currentBlock) {
            this.renderer.drawActiveBlock(this.currentBlock);
        }

        if (this.nextBlock) {
            this.renderer.drawNextBlock(this.nextBlock);
        }

        this.renderer.drawStats(this.score, this.level, this.gameBoard.linesCleared);
    }

    moveBlock(dx, dy) {
        if (this.isPaused || this.gameOver) return;

        const newBlock = Object.assign(Object.create(Object.getPrototypeOf(this.currentBlock)), this.currentBlock);
        newBlock.move(dx, dy);

        if (this.gameBoard.isValidPosition(newBlock)) {
            this.currentBlock = newBlock;
            return true;
        } else if (dy > 0) {
            // 如果是向下移动且不能移动，则固定方块
            this.lockBlock();
            return false;
        }

        return false;
    }

    rotateBlock() {
        if (this.isPaused || this.gameOver) return;

        const newBlock = Object.assign(Object.create(Object.getPrototypeOf(this.currentBlock)), this.currentBlock);
        newBlock.rotate();

        // 尝试旋转，如果不行则尝试左右移动后再旋转（墙踢）
        if (this.gameBoard.isValidPosition(newBlock)) {
            this.currentBlock = newBlock;
        } else {
            // 尝试向左移动
            newBlock.move(-1, 0);
            if (this.gameBoard.isValidPosition(newBlock)) {
                this.currentBlock = newBlock;
            } else {
                // 尝试向右移动
                newBlock.move(2, 0);
                if (this.gameBoard.isValidPosition(newBlock)) {
                    this.currentBlock = newBlock;
                }
            }
        }
    }

    hardDrop() {
        if (this.isPaused || this.gameOver) return;

        let dropDistance = 0;
        while (true) {
            const newBlock = Object.assign(Object.create(Object.getPrototypeOf(this.currentBlock)), this.currentBlock);
            newBlock.move(0, dropDistance + 1);

            if (!this.gameBoard.isValidPosition(newBlock)) {
                // 找到了最低点，将方块移动到该位置
                this.currentBlock.move(0, dropDistance);
                this.lockBlock();
                break;
            }
            dropDistance++;
        }
    }

    lockBlock() {
        // 将当前方块固定到游戏板上
        const linesCleared = this.gameBoard.placeBlock(this.currentBlock);

        // 更新分数
        this.updateScore(linesCleared);

        // 生成新方块
        this.currentBlock = this.nextBlock;
        this.nextBlock = new Block();

        // 检查游戏是否结束
        if (!this.gameBoard.isValidPosition(this.currentBlock)) {
            this.gameOver = true;
            this.showOverlay('GAME OVER');
        }
    }

    updateScore(linesCleared) {
        if (linesCleared > 0) {
            // 经典俄罗斯方块计分规则
            const linePoints = [40, 100, 300, 1200]; // 1, 2, 3, 4行的分数
            this.score += linePoints[Math.min(linesCleared, 4) - 1] * this.level;

            // 更新显示
            this.scoreElement.textContent = this.score;

            // 每清除10行升一级
            const newLevel = Math.floor(this.gameBoard.linesCleared / 10) + 1;
            if (newLevel > this.level) {
                this.level = newLevel;
                this.levelElement.textContent = this.level;

                // 提高游戏速度
                this.dropInterval = Math.max(100, 1000 - (this.level - 1) * 100);
            }
        }
    }

    togglePause() {
        if (this.gameOver) return;

        this.isPaused = !this.isPaused;

        if (this.isPaused) {
            this.showOverlay('PAUSED');
        } else {
            this.hideOverlay();
        }
    }

    resetGame() {
        this.gameBoard.reset();
        this.currentBlock = new Block();
        this.nextBlock = new Block();
        this.score = 0;
        this.level = 1;
        this.dropInterval = 1000;
        this.gameOver = false;
        this.isPaused = false;

        // 更新显示
        this.scoreElement.textContent = this.score;
        this.levelElement.textContent = this.level;
        this.hideOverlay();
    }

    showOverlay(text) {
        this.overlayText.textContent = text;
        this.overlay.classList.remove('hidden');
    }

    hideOverlay() {
        this.overlay.classList.add('hidden');
    }
}

// 当页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    const game = new Game();
});